package util

import (
	"gopkg.in/redis.v4"
	"encoding/json"
	"time"
	"www2/cfg"
)

var Client *redis.Client
func init(){
	initCacheClient(*cfg.RedisStr,"", 1)
}
func initCacheClient(addr string, passwd string, db int){
	Client = redis.NewClient(&redis.Options{
		Addr: addr,
		Password: passwd,
		DB: db,
	})
}


func Get1(key string,expires time.Duration, fetch func()(interface{}))([]byte) {

	data,err := Client.Get(key).Bytes()
	if err != redis.Nil {
		/*var rst interface{}
		err =json.Unmarshal(data, &rst)
		return rst*/
		//log.Println("GOT IT FROM CACHE")
		return data
	}

	var d interface{}
	d = fetch();

	data, err = json.Marshal(d)
	if err != nil {
		panic(err)
	}

	err = Client.Set(key, data, expires).Err()
	if err != nil {
		panic(err)
	}
	return data
}
